package socksproxy.netty.proxy_wangZha.proxy2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class Proxy2HandlerProxy extends ChannelInboundHandlerAdapter {
	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		 System.out.println("目标服务器返回给我的信息是：" + msg);
	        System.out.println("代理服务器2建立与网闸2的通道传递返回数据....");
	        EventLoopGroup workerGroup = new NioEventLoopGroup();

	        try {
	            Bootstrap b = new Bootstrap();
	            b.group(workerGroup);
	            b.channel(NioSocketChannel.class);
	            b.option(ChannelOption.SO_KEEPALIVE, true);
	            b.handler(new ChannelInitializer<SocketChannel>() {
	                @Override
	                public void initChannel(SocketChannel ch) throws Exception {
	                	ChannelPipeline pipeline = ch.pipeline();
						pipeline.addLast("frameDecoder",
								new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0,
										4, 0, 4));
						pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
						pipeline.addLast("decoder",
								new StringDecoder(CharsetUtil.UTF_8));
						pipeline.addLast("encoder",
								new StringEncoder(CharsetUtil.UTF_8));
	                }
	            });
	            // Start the client.
	            ChannelFuture f = b.connect("192.168.50.239", 3344).sync();
	            System.out.println("代理服务器2开始像网闸2传递数据....");
	            f.channel().writeAndFlush(msg);
	            f.addListener(new ChannelFutureListener() {
	                @Override
	                public void operationComplete(ChannelFuture future) throws Exception {
	                    System.out.println("===========数据发送成功==========");
	                }
	            });
	            f.channel().closeFuture().sync();
	        } catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
	            workerGroup.shutdownGracefully();
	        }
        ctx.close();
    }
}
